<?php
Authenticate::requireAccounting();
$db = Db::getInstance();
$db->autocommit(false);
$pdo = Db::getPDO();
$pdo->beginTransaction();
try {
	if($_SERVER['REQUEST_METHOD'] == 'DELETE'){
		parse_str(file_get_contents("php://input"), $formData);
		if(!Invoice::del($formData['id'])){
			throw new Exception("Delete Invoice id {$formData['id']} failed");
		}
		$query = sprintf("DELETE FROM PaymentInvoice WHERE invoiceId='%s'", $db->real_escape_string($formData['id']));
		if(!$db->query($query)){
			throw new Exception($db->error);
		}
		$db->commit();
		echo json_encode(array('success'=> true));
	}
	else if($_SERVER['REQUEST_METHOD'] == 'PUT'){
		parse_str(file_get_contents("php://input"), $formData);
		$editData = $formData;
		unset($editData['id']);
		if(!Invoice::edit($formData['id'], $editData)){
			throw new Exception("Edit Invoice id {$formData['id']} failed");
		}
		$db->commit();
		echo json_encode(array('success'=> true));
	}
	else if($_SERVER['REQUEST_METHOD']=='GET'){
		$invoice = Invoice::getInvoiceById($_GET['id']);
		$invoice['account'] = Account::get($invoice['accountId']);
		echo json_encode($invoice);
	}
	else if($_SERVER['REQUEST_METHOD']=='OPTIONS'){
		parse_str(file_get_contents("php://input"), $formData);
		if($formData['action']=='paid'){
			$data = $formData['data'];
            Invoice::instance()->edit($data['id'], array('status'=> $data['status']));
			$db->commit();
            $pdo->commit();
			echo json_encode(array('success'=> true));
		}
		else if($formData['action']=='paidTechnic'){
			$data = $formData['data'];
			Invoice::instance()->edit($data['id'], array('status'=> $data['status']));
			ConfigInvoice::instance()->add(array('invoiceId'=> $data['id'], 'status'=> 0));
			$db->commit();
            $pdo->commit();
			echo json_encode(array('success'=> true));
		}
	}
} 
catch(Exception $ex){
	$db->rollback();
	echo json_encode(array('success'=> false));
    throw $ex;
}